package com.haste;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haste.config.RedisConfig;
import com.haste.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.concurrent.TimeUnit;

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class TestRedis {

    @Autowired
    @Qualifier("redisTemplate") //防止歧义
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private User user;

    @Test
    public void testRedis(){
//        redisTemplate.opsForValue();//操作字符串
//        redisTemplate.opsForList();//操作list
//        redisTemplate.opsForGeo();//操作地理位置
//        redisTemplate.opsForHash();//操作hash
//        redisTemplate.opsForSet();//操作set
//        redisTemplate.opsForHyperLogLog();//操作HyperLogLog
//        redisTemplate.opsForZSet();//操作ZSet
        redisTemplate.opsForValue().set("name","haste");
        System.out.println(redisTemplate.opsForValue().get("name"));
    }

    @Test
    public void test1() throws JsonProcessingException {
        redisTemplate.getConnectionFactory().getConnection().flushDb();
        user.setName("黑斯特");
        user.setAge(18);
//        String s = new ObjectMapper().writeValueAsString(user);
        redisTemplate.opsForValue().set("user",user);
        System.out.println(redisTemplate.opsForValue().get("user"));

    }

    //设置过期时间，第三个参数指定时间的单位。只能设置存在的key，不存在的key将设置失败，设置成功后，将移除设置的key，原有的key也将不存在
    @Test
    public void test2(){
        Boolean result = redisTemplate.expire("name", 200, TimeUnit.SECONDS);
        System.out.println(result);
    }

    //查看过期时间
    @Test
    public void test3(){
        String name = "name";
        System.out.println(name.getBytes().length);
        System.out.println(redisTemplate.getConnectionFactory().getConnection().ttl(name.getBytes()));
    }

    //设置一个key
    @Test
    public void test4(){
        redisTemplate.opsForValue().set("name","haste");
    }
}
